package com.tmc.service.common;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.constant.NoticeConstant.NoticeStatus;
import com.tmc.dao.impl.NoticeDaoImpl;
import com.tmc.entity.common.EthNotice;
import com.tmc.util.DateUtil;
import com.tmc.util.ObjectUtil;
import com.tmc.vendor.asms.util.Asms10000Util;

@Service
@Transactional
public class NoticeServiceImpl {

	private Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private NoticeDaoImpl dao;

	public CommonResult save(ContextInfo context, EthNotice notice) throws Exception {
		CommonResult check = this.check(notice);
		if (!check.isSuccess()){
			logger.error(check.getMessage());
			return check;
		}
		if (notice.getNoticeId() == null) {
			ObjectUtil.setBaseInfo(notice, context);
			dao.insert(notice);
		} else {
			ObjectUtil.updateBaseInfo(notice, context);
			dao.update(notice);
		}
		return CommonResult.makeSuccess();
	}

	private CommonResult check(EthNotice notice) {
		if (ObjectUtil.noText(notice.getSendTarget())){
			return CommonResult.makeFail("发送对象不能为空！");
		}
		if (notice.getToSendTime() == null){
			return CommonResult.makeFail("发送时间不能为空！");
		}
		if (ObjectUtil.noText(notice.getContent())){
			return CommonResult.makeFail("发送内容不能为空！");
		}
		return CommonResult.makeSuccess();
	}

	public List<EthNotice> findWaitSend(int max) {
		EthNotice cond = new EthNotice();
		cond.setStatus(NoticeStatus.WAITING.getStatus());
		cond.setToSendTime(DateUtil.toLongDate(new Date()));
		return dao.findByCon(null, cond, max);
	}

	public void run() {
		logger.error("执行一次发送通知！");
		List<EthNotice> notices = this.findWaitSend(5);
		if (notices == null || notices.isEmpty()) {
			return;
		}
		for (EthNotice notice : notices) {
			send(notice);
		}
	}

	public void send(EthNotice notice) {
		try {
			CommonResult result = Asms10000Util.sendSms(notice);
			if (result.isSuccess()) {
				notice.setStatus(NoticeStatus.SUCCESS.getStatus());
				notice.setSendTime(DateUtil.toLongDate(new Date()));
			}
		} catch (Exception e) {
			notice.setStatus(NoticeStatus.FAIL.getStatus());
			logger.error("发送通知错误！", e);
		}
		
		ObjectUtil.updateBaseInfo(notice, null);
		dao.update(notice);
	}

}
